﻿using System;
using System.Text;

namespace NguyenHoa.Web.App_Code
{
  public sealed class VietnameseString
  {
    private static char[] m_delimiters = new char[] { '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '[', '}', ']', '|', '\\', ':', ';', '\'', '"', ',', '<', '.', '>', '?', '/', ' ' };
    private const string A = "áàảãạâấầẩậăắằẳẵặ";
    private const string D = "đ";
    private const string E = "éèẻẽẹêếềểệ";
    private const string I = "íìỉĩị";
    private const string O = "óòỏõọôốồổỗộơớờởỡợ";
    private const string U = "úùủũụưứừửữự";
    private const string Y = "ýỳỷỹỵ";

    public static string Convert(string source)
    {
      if (source == null) return null;
      if (source == String.Empty) return String.Empty;
      string[] words = source.Split(m_delimiters, StringSplitOptions.RemoveEmptyEntries);
      StringBuilder sb = new StringBuilder();
      foreach (string word in words)
      {
        sb.Append(ReplaceSignCharacter(word.ToLower()));
        sb.Append('-');
      }
      return sb.ToString(0, sb.Length - 1);
    }

    private static string ReplaceSignCharacter(string source)
    {
      StringBuilder sb = new StringBuilder();
      foreach (char s in source)
      {
        if (A.IndexOf(s) > -1)
        {
          sb.Append('a');
        }
        else if (D.IndexOf(s) > -1)
        {
          sb.Append('d');
        }
        else if (E.IndexOf(s) > -1)
        {
          sb.Append('e');
        }
        else if (I.IndexOf(s) > -1)
        {
          sb.Append('i');
        }
        else if (O.IndexOf(s) > -1)
        {
          sb.Append('o');
        }
        else if (U.IndexOf(s) > -1)
        {
          sb.Append('u');
        }
        else if (Y.IndexOf(s) > -1)
        {
          sb.Append('y');
        }
        else
        {
          sb.Append(s);
        }
      }
      return sb.ToString();
    }
  }
}
